﻿using Usido.CRM.Core.Extensions;
using Usido.CRM.Core.Models;
using System;
using System.Data;
using System.Data.SqlClient;

namespace Usido.CRM.Core.DbHelper
{
    /// <summary>
    /// 数据库连接工厂类
    /// </summary>
    public class ConnectionFactory
    {
        /// <summary>
        /// 获取数据库连接
        /// </summary>
        /// <param name="dbtype">数据库类型</param>
        /// <param name="connectionString">数据库连接字符串</param>
        /// <returns>数据库连接</returns>
        public static IDbConnection CreateConnection(string dbType, string connectionString)
        {
            if (dbType.IsNullOrWhiteSpace())
                throw new ArgumentNullException("数据库类型不能为空");
            if (connectionString.IsNullOrWhiteSpace())
                throw new ArgumentNullException("数据库连接字符串不能为空");
            var databaseType = GetDataBaseType(dbType);
            return CreateConnection(databaseType, connectionString);
        }

        /// <summary>
        /// 获取数据库连接
        /// </summary>
        /// <param name="dbType">数据库类型</param>
        /// <param name="connectionString">数据库连接字符串</param>
        /// <returns>数据库连接</returns>
        public static IDbConnection CreateConnection(DatabaseType dbType, string connectionString)
        {
            IDbConnection connection = null;
            if (connectionString.IsNullOrWhiteSpace())
                throw new ArgumentNullException("数据库连接字符串不能为空");

            switch (dbType)
            {
                case DatabaseType.SqlServer:
                    connection = new SqlConnection(connectionString);
                    break;

                //case DatabaseType.MySQL:
                //    connection = new MySqlConnection(connectionString);
                //    break;

                //case DatabaseType.PostgreSQL:
                //    connection = new NpgsqlConnection(connectionString);
                //    break;

                default:
                    throw new ArgumentNullException($"目前还不支持{dbType.ToString()}数据库类型");
            }

            if (connection.State == ConnectionState.Closed)
                connection.Open();

            return connection;
        }

        /// <summary>
        /// 转换数据库类型
        /// </summary>
        /// <param name="dbtype">数据库类型字符串</param>
        /// <returns>数据库类型</returns>
        public static DatabaseType GetDataBaseType(string dbType)
        {
            if (dbType.IsNullOrWhiteSpace())
                throw new ArgumentNullException("数据库类型不能为空");

            DatabaseType returnValue = DatabaseType.SqlServer;

            foreach (DatabaseType item in Enum.GetValues(typeof(DatabaseType)))
            {
                if (item.ToString().Equals(dbType, StringComparison.OrdinalIgnoreCase))
                {
                    returnValue = item;
                    break;
                }
            }

            return returnValue;
        }
    }
}